<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

echo "load Events.php\n";
require_once __DIR__ . '/DirRoot/Cmd.php';
require_once __DIR__ . '/DirRoot/Mgr.php';
require_once __DIR__ . '/DirRoot/Protocol.php';

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
        //Gateway::sendToAll("$client_id login\r\n");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
        // 向所有人发送 
        //Gateway::sendToAll("$client_id said $message\r\n");

      echo "client_id:$client_id:" , "uid:", Gateway::getUidByClientId($client_id), "\n";

      //获取协议名
      $index = strpos($message,"{");
      $msg_name = substr($message, 0, $index);

      //获取协议体
      $str_len = strlen($message);
      $msg_body_raw = substr($message, $index, $str_len - $index);
      $msg_body = json_decode($msg_body_raw, false);//false:解析为对象

      //不是握手协议，不打印
      if($msg_name != "handshake"){
        echo $msg_name, "=>";
        print_r($msg_body);
      }

      //var_dump($msg_body); 带类型的打印

      //echo "index:", $index, " str_len:", $str_len, " msg_name:", $msg_name, " msg_body:", $msg_body_raw, "\n";
      

      $cmd = $GLOBALS['Cmd_center']["cmd_$msg_name"];
      //var_dump($cmd);
      

      if(!isset($cmd))
      {
          static::sendToClient($client_id, "notify_error", array('ret'=>NetErrorCode::Error, 'reason'=>"unknow msg:$msg_name"));
          //throw new \Exception("$msg_name is not set");
          echo "fatal error:$msg_name is not set\n";
          return;
      }

      $cmd->client_id = $client_id;
      $ret = $cmd->onCmd($msg_body);
      unset($cmd->client_id);
      if(!isset($ret)){
          return;
      }
      static::sendToClient($client_id, "{$msg_name}_rsp", $ret);
      // switch($msg_name)
      // {
      //     // 客户端回应服务端的心跳
      //     case 'login':
      //       $msg_body = array(
      //         'ret'=>0,
      //         'reason'=>"userid",
      //       );
      //       Events::sendToClient($client_id, "login", $msg_body);
      //       break;
      //     // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
      //     case 'handshake':
      //       $msg_body = array(
      //         'msg'=>"rsp",
      //       );
      //       Events::sendToClient($client_id, "handshake", $msg_body);
      //       break;
      //     default:
      //       Events::sendToClient($client_id, "handshake", array('msg'=>"unknow msg:$msg_name",));
      //       echo "can not handle:", $msg_name, "\n";
      //       break;
      // }
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       //GateWay::sendToAll("$client_id logout\r\n");

      // $uid = Gateway::getUidByClientId($client_id);
      // if(isset($uid)){
      //     Gateway::unbindUid($client_id, $uid);
      //     echo "unbind:", $uid;
      // }else{
      //     echo "no need to unbind:", $uid;
      // }

      $group_mgr = $GLOBALS['GroupMgr'];
      $group_mgr->leaveGroupWhenOffline();
   }

   public static function sendToAll($client_id, $msg_name, $msg_body){
    
   }

   public static function sendToCurrentClient($msg_name, $msg_body){
      Gateway::sendToCurrentClient(static::wrapMsg($msg_name, $msg_body));
   }

   public static function sendToClient($client_id, $msg_name, $msg_body){
      Gateway::sendToClient($client_id, static::wrapMsg($msg_name, $msg_body));
   }

   public static function sendToGroup($group_id, $msg_name, $msg_body){
      Gateway::sendToGroup($group_id, static::wrapMsg($msg_name, $msg_body));
   }

  public static function wrapMsg($msg_name, $msg_body){
        $json_encode_msg = json_encode($msg_body);
        return "$msg_name$json_encode_msg";
  }

}
